{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c54a393e",
   "metadata": {},
   "source": [
    "# 批量预测\n",
    "\n",
    "1. 需要指定要批量预测的样本。\n",
    "\n",
    "   1. 自己手动指定。\n",
    "   2. 通过`mydir`参数循环找到指定目录下的所有图片数据。\n",
    "   \n",
    "2. 指定Onekey训练好的目录路径，对应到`config_path参数`，精确到`viz`目录。\n",
    "> 例如：path2yours/20220802/inception_v3_bb/viz"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0146753",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "POSSIBLE_IMG = ['.jpg', '.jpeg', '.png', '.bmp']\n",
    "\n",
    "my_dir = r''\n",
    "config_path = r''\n",
    "samples = []\n",
    "for root, _, files in os.walk(my_dir):\n",
    "    samples.extend([os.path.join(root, f) for f in files if os.path.splitext(f)[-1] in POSSIBLE_IMG])\n",
    "print(len(samples))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2389f96c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "from onekey_algo.classification.eval_classification import init as clf_init\n",
    "from onekey_algo.classification.eval_classification import inference as clf_inference\n",
    "\n",
    "config_path = r'D:/20220531-Sychoah/models/20220802/inception_v3_bb/viz'\n",
    "model, transformer, labels, device = clf_init(config_path=config_path)\n",
    "results = clf_inference(samples, model, transformer, labels, device)\n",
    "# print(json.dumps(results, ensure_ascii=False, indent=True))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cdcd6b8",
   "metadata": {},
   "source": [
    "## 保存结果\n",
    "\n",
    "结果分成3列，分别是fname，prob，label\n",
    "\n",
    "* fname: 样本名称，注意只有文件名，注意不同文件夹的差异。\n",
    "* prob：预测的每个标签的概率。\n",
    "* label：预测标签（概率最大的哪一个）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5911fe81",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "r = pd.DataFrame(results, columns=['fname', 'prob', 'label'])\n",
    "r.to_csv('predict.csv', index=False)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
